package controller;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.dao.auth.EmployeeAuthImpl;
import model.dao.auth.UserAuth;
import model.dao.auth.UserAuthImpl;
import model.user.User;

import validator.LoginValidator;

public class LoginController{
	
	public void login(HttpServletRequest req, HttpServletResponse res, ServletContext context, HttpSession session)
			throws ServletException, IOException {
		
		HashMap<String, String> hashmap = new HashMap<String, String>();
		LoginValidator v = new LoginValidator();
		
		if (req.getParameter("submit") != null)
			hashmap = v.validate(req.getParameter("username"), req.getParameter("password"));
		
		//If form ok
		if (hashmap.size() == 0) {
			User u = null;
			//If admin
			if (req.getParameter("admin")!=null && req.getParameter("admin").equals("1")) {
				UserAuth eai=new EmployeeAuthImpl();
				u=eai.getEmployee(req.getParameter("username"), req.getParameter("password"));	
				if (u == null) {
					hashmap.put("general", "username and/or password incorrect");
				}
				else {
					session.setAttribute("userId", u.getUser());
					session.setAttribute("username", u.getUserName());
					session.setAttribute("firstname", u.getFirstName());
					session.setAttribute("lastname", u.getLastName());
					session.setAttribute("admin", true);
					res.sendRedirect("/r56_remonditeenus/s");
					return;
				}
			//if user
			}else if(req.getParameter("admin")!=null && req.getParameter("admin").equals("0")){
				UserAuth uai=new UserAuthImpl();
				u=uai.getUser(req.getParameter("username"), req.getParameter("password"));
				if (u == null) {
					hashmap.put("general", "username and/or password incorrect");
				}
				else {
					session.setAttribute("userId", u.getUser());
					session.setAttribute("username", u.getUserName());
					session.setAttribute("firstname", u.getFirstName());
					session.setAttribute("lastname", u.getLastName());
					session.setAttribute("customer_id", u.getCustomer_id());
					res.sendRedirect("/r56_remonditeenus/s");
					return;
				}
			}
		}

		req.setAttribute ("errors", hashmap);
		context.getRequestDispatcher("/login_form.jsp").forward(req, res);
		
	}

}
